<?php
/**
 * Joomla! 1.5 component JoomGPSTracks
 *
 * @version $Id: tracks.php 2009-06-24 15:40:19 svn $
 * @author Michael Pfister
 * @package joomGPStracks
 * @subpackage frontend
 * @license GNU/GPL
 * @filesource
 *
 */
 
defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.model');

class JoomgpstracksModelTracks extends JModel  {
	/**
	 * tracks data array
	 *
	 * @var array
	 */
	var $_data = null;

	/**
	 * tracks total
	 *
	 * @var integer
	 */
	var $_total = null;

    
    /**
	 * Constructor
	 */
	function __construct() {
        
		parent::__construct();
    }

    function getData($limit, $limitstart)  {
		// Lets load the content if it doesn't already exist
		if (empty($this->_data))
		{
			$query = $this->_buildQuery();
			$this->_data = $this->_getList($query, $limitstart, $limit);
		}

		return $this->_data;
    }


    /**
     *
     * @return string
     */
    function getTotal()  {

		// Lets load the content if it doesn't already exist
		if (empty($this->_total))
		{
			$query = $this->_buildQuery();
			$this->_total = $this->_getListCount($query);
		}

		return $this->_total;
    }

    /**
     *
     * @global array $mainframe
     * @return string
     */
    function _buildQuery()  {
        global $mainframe;
        $user		=& JFactory::getUser();

		$orderby	= $this->_buildContentOrderBy();
        $where      = $this->_buildContentWhere();
        $userwhere       = "";

        if(JRequest::getVar('layout') == 'user' && !$where)  {
            $userwhere = " WHERE uid='".$user->get('id')."'";
        } else if(JRequest::getVar('layout') == 'user' && $where)  {
            $userwhere = " AND uid='".$user->get('id')."'";
        }

        $db =& JFactory::getDBO();

        $query = "SELECT a.*, b.title AS cat, b.image AS image, c.username AS user"
                . "\n FROM #__gps_tracks AS a"
                . "\n LEFT JOIN #__gps_cats AS b ON a.catid=b.id"
                . "\n LEFT JOIN #__users AS c ON a.uid=c.id"
                . $where
                . $userwhere
                . $orderby
                ;

        return $query;
    }

    /**
     *
     * @global array $mainframe
     * @global string $option
     * @return string
     */
 	function _buildContentOrderBy()
	{
		global $mainframe, $option;

		$filter_order		= $mainframe->getUserStateFromRequest( $option.'filter_order',		'filter_order',		'ordering',	'cmd' );
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( $option.'filter_order_Dir',	'filter_order_Dir',	'',				'word' );

		if ($filter_order == 'ordering'){
			$orderby 	= ' ORDER BY ordering '.$filter_order_Dir;
		} else {
			$orderby 	= ' ORDER BY '.$filter_order.' '.$filter_order_Dir.' , id ';
		}

		return $orderby;
	}

    /**
     *
     * @global array $mainframe
     * @global string $option
     * @return string
     */
    function _buildContentWhere()  {

        global $mainframe, $option;

        $search =& JRequest::getVar('search');
        $where = array();
        $db =& JFactory::getDBO();

        if($search)  {
            $where[] = 'LOWER(a.title) LIKE '.$db->Quote( '%'.$db->getEscaped( $search, true ).'%', false );
            $where[] = 'LOWER(b.title) LIKE '.$db->Quote( '%'.$db->getEscaped( $search, true ).'%', false );
            $where[] = 'LOWER(c.username) LIKE '.$db->Quote( '%'.$db->getEscaped( $search, true ).'%', false );
        }
        $where 		= ( count( $where ) ? ' WHERE ' . implode( ' OR ', $where ) : '' );

        return $where;
    }

    /**
     *
     * @global <type> $mainframe
     * @return <type> 
     */
    function getCats()  {
        global $mainframe;

        $db =& JFactory::getDBO();

        $query = "SELECT id, parent, title FROM #__gps_cats ORDER BY ordering ASC";

        $db->setQuery($query);
        $rows = $db->loadObjectList();
        $limit = count($rows);
        $children = array();
	foreach ($rows as $v ) {
		$pt 	= $v->parent;
		$list 	= @$children[$pt] ? $children[$pt] : array();
		array_push( $list, $v );
		$children[$pt] = $list;
	}
        $list = JHTML::_('menu.treerecurse', 0, '', array(), $children );
        $list = array_slice($list,0,$limit);
        $cats = array();
        foreach($list as $cat)  {
            if($cat->treename == NULL) {
                $title = $cat->title;
            } else {
                $title = "&bull; ".$cat->title;
            }
            array_push($cats,array('id' => $cat->id, 'title' => $title));
        }
        return $cats;
    }

    /**
     *
     * @global object $mainframe
     * @return boolean
     */
    function saveTrack()  {
        global $mainframe;

        jimport('joomla.filesystem.file');

        $db =& JFactory::getDBO();
        $user =& JFactory::getUser();
        
        // get the post data
        $catid =& JRequest::getInt('catid');
        $level =& JRequest::getInt('level');
        $title =& JRequest::getVar('title');
        $terrain =& JRequest::getVar('terrain');
        if(count($terrain > 0)):
            $terrain = implode(',', $terrain);
        endif;
        $desc =& JRequest::getVar( 'description', '', 'post', 'string', JREQUEST_ALLOWRAW);
        $file =& JRequest::getVar('file', null, 'files', 'array');
        $uid = $user->get('id');
        $date = date("Y-m-d");
        $images =& JRequest::getVar('images', null, 'files', 'array');
        $access =& JRequest::getInt('access', 0);


            // upload the file
            $upload_dir = JPATH_SITE.DS."components".DS."com_joomgpstracks".DS."uploads".DS;
            $filename = JFile::makeSafe($file['name']);
            $filename = str_replace(' ', '_', $filename);
            if (!JFile::upload($file['tmp_name'], $upload_dir.strtolower($filename))) {
                echo "Upload failed!";
            } else {
                chmod($upload_dir.strtolower($filename), 0777);
            }

            // get the start coordinates
            $gps = new gpsClass();
            $gps->gpsFile = "./components/com_joomgpstracks/uploads/".strtolower($filename);
            if($gps->getStartCoordinates())  {
                $start = $gps->getStartCoordinates();
            } else {
                echo "<script type='text/javascript'>alert('".JText::_('GPS_NO_SUPPORT')."');window.history.back(-1);</script>";
                exit;
            }

            $file = './components/com_joomgpstracks/uploads/'.strtolower($filename);
            $start_n = $start[1];
            $start_e = $start[0];
            $coords = $gps->getCoords($file);
            $distance = $gps->getDistance($coords);
            if($distance == NULL)  {
                echo "<script type='text/javascript'>alert('".$distance."');window.history.back(-1);</script>";
                exit;
            }

            // call the elevation function
            $ele = $gps->getElevation($coords);


            // images upload part
            $cfg = joomgpstracksHelper::getConfig();
            $types = explode(',',$cfg->type);
            if(count($images) > 0 )  {
                JFolder::create(JPATH_SITE.DS.'images'.DS.'joomgpstracks'.DS.md5($title),0777);
                $img_dir = JPATH_SITE.DS.'images'.DS.'joomgpstracks'.DS.md5($title);
                foreach($images['name'] as $key => $value)  {
                    $ext = explode('.',$images['name'][$key]);
                    if(in_array($ext[1], $types)) {
                        $path = $img_dir.DS.strtolower($images['name'][$key]);
                        (createImage($images['tmp_name'][$key], $ext[1], $path));
                    }
                }
            }



            $query = "INSERT INTO #__gps_tracks SET"
                    . "\n uid='".$uid."',"
                    . "\n catid='".$catid."',"
                    . "\n title='".$title."',"
                    . "\n file='".strtolower($filename)."',"
                    . "\n terrain='".$terrain."',"
                    . "\n description='".$desc."',"
                    . "\n date='".$date."',"
                    . "\n start_n='".$start_n."',"
                    . "\n start_e='".$start_e."',"
                    . "\n distance='".$distance."',"
                    . "\n ele_asc='".$ele[0]."',"
                    . "\n ele_desc='".$ele[1]."',"
                    . "\n level='".$level."',"
                    . "\n access='".$access."'"
                    ;

            $db->setQuery($query);
            $db->query();

            if ($db->getErrorNum()) {
                echo $db->stderr();
                    return false;
                } else {
                    return true;
                }
            
    }

    /**
     *
     * @global <type> $mainframe
     * @return <type> 
     */
	function hit()
	{
		global $mainframe;

        $id =& JRequest::getInt('id');

		if ($id)
		{
			$tracks = & $this->getTable('gps_tracks');
			$tracks->hit($id);
			return true;
		}
		return false;
	}

    /**
     *
     * @global <type> $mainframe
     * @param <type> $id
     * @return <type>
     */
    function getTrack($id)  {
        global $mainframe;

        $db =& JFactory::getDBO();

        $query = "SELECT a.*, b.title AS cat, b.image AS image, c.username AS user"
                . "\n FROM #__gps_tracks AS a"
                . "\n LEFT JOIN #__gps_cats AS b ON a.catid=b.id"
                . "\n LEFT JOIN #__users AS c ON a.uid=c.id"
                . "\n WHERE a.id='" .$id. "'";

        $db->setQuery($query);
        $track = $db->loadObject();

        return $track;
    }

    /**
     *
     * @global <type> $mainframe
     * @param <type> $id
     * @param <type> $rate
     * @return <type> 
     */
    function vote($id, $rate)  {
        global $mainframe;

        $db =& JFactory::getDBO();

        $query = "INSERT INTO #__gps_votes SET"
                . "\n trackid='" .$id."',"
                . "\n rating='" .$rate."'"
                ;

        if($id && $rate):
            $db->setQuery($query);
            $db->query();
            return true;
        endif;

        return false;
    }

    /**
     *
     * @global <type> $mainframe
     * @param <type> $id
     * @return <type> 
     */
    function getVotes($id)  {
        global $mainframe;

        $class = array('nostar', 'onestar', 'twostar', 'threestar', 'fourstar', 'fivestar', 'sixstar', 'sevenstar', 'eightstar', 'ninestar', 'tenstar');
        
        $db =& JFactory::getDBO();
        // count votings
        $query = "SELECT COUNT(*) FROM #__gps_votes"
                . "\n WHERE trackid='" .$id. "'";

        $db->setQuery($query);
        $count = $db->loadResult();
        // sum rating
        $query = "SELECT SUM(rating) FROM #__gps_votes"
                . "\n WHERE trackid='" .$id. "'";

        $db->setQuery($query);
        $rating = $db->loadResult();
        if($count > 0)  {
            $rate = round(($rating/$count), 0);
        } else {
            $rate = 0;
        }



        $object = array("count" => $count,
                        "rate"  => $rate,
                        "class" => $class[$rate]);

        return $object;
    }

    function deleteTrack($id)  {
        global $mainframe;

        $db = JFactory::getDBO();

        $query = "DELETE FROM #__gps_tracks"
                . "\n WHERE id='".$id."'";

        $db->setQuery($query);
        if($db->query())  {
            return true;
        } else {
            return false;
        }
    }
    function updateTrack($id)  {
        global $mainframe;

        jimport('joomla.filesystem.file');

        $db =& JFactory::getDBO();
        $user =& JFactory::getUser();

        // get the post data
        $catid =& JRequest::getInt('catid');
        $level =& JRequest::getInt('level');
        $title =& JRequest::getVar('title');
        $terrain =& JRequest::getVar('terrain');
        if(count($terrain > 0)):
            $terrain = implode(',', $terrain);
        endif;
        $desc =& JRequest::getVar( 'description', '', 'post', 'string', JREQUEST_ALLOWRAW);
        $images =& JRequest::getVar('images', null, 'files', 'array');
        $access =& JRequest::getInt('access', 0);

        // images upload part
        $cfg = joomgpstracksHelper::getConfig();
        $types = explode(',',$cfg->type);
        if($images)  {
            if(!JFolder::exists(JPATH_SITE.DS.'images'.DS.'joomgpstracks'.DS.md5($title))) {
                JFolder::create(JPATH_SITE.DS.'images'.DS.'joomgpstracks'.DS.md5($title),0777);
            }
            $img_dir = JPATH_SITE.DS.'images'.DS.'joomgpstracks'.DS.md5($title).DS;
            foreach($images['name'] as $key => $value)  {
                $ext = explode('.',$images['name'][$key]);
                if(in_array($ext[1], $types)) {
                    $path = $img_dir.DS.strtolower($images['name'][$key]);
                    (createImage($images['tmp_name'][$key], $ext[1], $path));
                }
            }
        }


            $query = "UPDATE #__gps_tracks SET"
                    . "\n catid='".$catid."',"
                    . "\n title='".$title."',"
                    . "\n terrain='".$terrain."',"
                    . "\n description='".$desc."',"
                    . "\n level='".$level."',"
                    . "\n access='".$access."'"
                    . "\n WHERE id='".$id."'"
                    ;

            $db->setQuery($query);
            $db->query();

            if ($db->getErrorNum()) {
                echo $db->stderr();
                    return false;
                } else {
                    return true;
                }
    }

    /**
     *
     * @global object $mainframe
     * @return array
     */
    function getTerrain()  {
        global $mainframe;

        $db = JFactory::getDBO();

        $query = "SELECT * FROM #__gps_terrain ORDER BY title ASC";

        $db->setQuery($query);
        $row = $db->loadObjectList();

        return $row;
    }

    /**
     *
     * @global object $mainframe
     * @param int $id
     * @param string $order
     * @return array
     */
    function getComments($id, $order)  {
        global $mainframe;

        $db = JFactory::getDBO();
        $query = "SELECT * FROM #__gps_comments WHERE"
                . "\n tid='".$id."'"
                . "\n AND published='1'"
                . "\n ORDER BY date ".$order
                ;
        $db->setQuery($query);
        $result = $db->loadObjectList();

        return $result;
    }

    /**
     *
     * @param object $cfg
     */
    function addcomment($cfg)  {
        JHTML::_('behavior.formvalidation');
        $editor =& JFactory::getEditor('tinymce');
        $editor_params = array('theme' => 'simple');
        $user =& JFactory::getUser();
        $id = JRequest::getInt('id');
        ?>
        <script language="javascript">
        function myValidate(f) {
                if (document.formvalidator.isValid(f)) {
                        f.check.value='<?php echo JUtility::getToken(); ?>';//send token
                        return true;
                }
                else {
                        alert('<?php echo JText::_('GPS_FILLOUT'); ?>');
                }
                return false;
        }
        </script>

        <form class='form-validate' id='adminform' name='adminform' action='index.php?option=com_joomgpstracks' method='post' onSubmit='return myValidate(this);'>
                    <table class='comment-form'>
                    <thead>
                        <tr><th colspan='2'><b><?php echo JText::_('GPS_WRITE_COMMENT'); ?></b></th></tr>
                    </thead>
                    <tbody>
                        <tr>
                        <td><label for='name'><?php echo JText::_('Name'); ?>*</label></td><td><input type='text' name='name' id='name' size='20' value='<?php echo $user->get('name'); ?>' class='required' maxlength='50' /></td>
                        </tr><tr>
                        <td><label for='email'><?php echo JText::_('e-mail'); ?>*</label></td><td><input type='text' name='email' id='email' size='30' value='<?php echo $user->get('email'); ?>' class='required validate-email' maxlength='50' /></td>
                        </tr><tr>
                        <td><label for='title'><?php echo JText::_('GPS_TITLE'); ?>*</label></td><td><input type='text' name='title' id='title' size='40' value='' class='required' maxlength='80' /></td>
                        </tr><tr>
                        <td><label for='text'><?php echo JText::_('GPS_TEXT'); ?>*</label></td><td><?php echo $editor->display('text', '', '400', '100', '10', '10', false, $editor_params); ?></td>
                        </tr>
                        <?php if($cfg->captcha == 1): ?>
                        <tr><td><img src='index.php?option=com_joomgpstracks&task=displayimg' ></td><td><input type="text" name="word" value="" size="10" class="required" /> <?php echo JText::_('GPS_CAPTCHA_INFO'); ?></td></tr>
                        <?php endif; ?>
                        <tr><td colspan='2' align='right'><input type='submit' value='senden' name='submit' class='button' /></td></tr>
                    </tbody>
                    </table>
                    <?php echo JHTML::_( 'form.token' ) . "\n"; ?>
                    <input type='hidden' name='controller' value='tracks' />
                    <input type='hidden' name='task' value='savecomment' />
                    <input type='hidden' name='id' value='<?php echo $id; ?>' />
                </form>
                <?php
       }

       /**
        *
        * @global object $mainframe
        * @param int $id
        * @return boolean
        */
       function savecomment($id, $cfg)  {
           global $mainframe;

           $name =& JRequest::getVar('name');
           $email =& JRequest::getVar('email');
           $title =& JRequest::getVar('title');
           $text =& JRequest::getVar( 'text', '', 'post', 'string', JREQUEST_ALLOWRAW);

           $db =& JFactory::getDBO();
           $query = "INSERT INTO #__gps_comments SET"
                    . "\n tid='".$id."',"
                    . "\n user='".$name."',"
                    . "\n email='".$email."',"
                    . "\n title='".$title."',"
                    . "\n text='".$text."',"
                    . "\n published='1'"
                    ;

           $db->setQuery($query);
           $db->query();
           
            if ($db->getErrorNum()) {
                echo $db->stderr();
                return false;
            } else {
                return true;
            }

           // send autor email if set
           if($cfg->inform_autor == 1)  {
               $jcfg = JFactory::getConfig();
               $user = $this->getAutorData($id);
               $email = $autor->email;
               $from = $jcfg->mailfrom;
               $sender = $jcfg->fromname;
               $link = JURI::base()."index.php?option=com_joomgpstracks&view=tracks&layout=track&id=".$id;
               $msg = JText::_('GPS_CMAIL_MSG');
               $body = sprintf($msg, $link);
               $subject = JText::_('GPS_CMAIL_SUBJECT');

               // clean the email data
               $subject = JMailHelper::cleanSubject($subject);
               $body = JMailHelper::cleanBody($body);
               $sender = JMailHelper::cleanAdress($sender);

               JUtility::sendMail($from, $sender,$email,$subject,$body);
           }
       }

       function getAutorData($id)  {
           global $mainframe;

           $db = JFactory::getDBO();
           $query = "SELECT a.uid, b.name, b.email FROM #__gps_tracks AS a"
                    . "\n LEFT JOIN #__users AS b ON a.uid=b.id"
                    . "\n WHERE a.id='".$id.'"'
                    ;

           $db->setQuery($query);
           $user = $db->loadObject();

           return $user;

       }

       function createLevelImg($level)  {
           $string = "";
           for($i=0; $i<$level; $i++) {
               $string .= '<span class="levelimg"><img src="'.JURI::base().'components/com_joomgpstracks/assets/images/spacer.gif" width="15" height="15"></span>';
           }

           return $string;
       }
}

?>
